package handler

import (
	"awesomeProject/dao"
	"awesomeProject/pojo"
	"awesomeProject/utils"
	"encoding/json"
	"log"
	"net/http"
)

// 登录处理器
func LoginHandler(w http.ResponseWriter, r *http.Request) {
	defer func() {
		if err := recover(); err != nil {
			log.Printf("理器发生panic: %v", err)
			utils.CustomError(w, "理器发生panic", http.StatusInternalServerError)
		}
	}()

	if r.Method != "POST" {
		utils.CustomError(w, "方法不允许", http.StatusMethodNotAllowed)
		return
	}

	var req struct {
		Username string `json:"username"`
		Password string `json:"password"`
	}

	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		utils.CustomError(w, "传递参数错误", http.StatusBadRequest)
		return
	}

	// 查询用户信息
	var user pojo.User
	err := dao.Db.QueryRow("SELECT user_id, username, realname, password_hash FROM users WHERE username = ?", req.Username).
		Scan(&user.UserID, &user.Username, &user.Realname, &user.PasswordHash)
	if err != nil {
		utils.CustomError(w, "用户名不正确", http.StatusUnauthorized)
		return
	}

	// 验证密码
	if utils.HashPwd(req.Password) != user.PasswordHash {
		utils.CustomError(w, "密码错误", http.StatusUnauthorized)
		return
	}

	// 生成JWT token
	token, err := utils.GenerateToken(user.UserID, user.Realname)
	if err != nil {
		utils.CustomError(w, "生产token失败", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(200)
	// 返回token和用户信息
	json.NewEncoder(w).Encode(map[string]interface{}{
		"status":   0,
		"msg":      "OK",
		"token":    token,
		"user_id":  user.UserID,
		"realname": user.Realname,
	})
}

// 更新token时间
func UpdateTokenHandler(w http.ResponseWriter, r *http.Request) {
	defer func() {
		if err := recover(); err != nil {
			log.Printf("理器发生panic: %v", err)
			utils.CustomError(w, "理器发生panic", http.StatusInternalServerError)
		}
	}()

	if r.Method != "POST" {
		utils.CustomError(w, "方法不允许", http.StatusMethodNotAllowed)
		return
	}

	var req struct {
		Token string `json:"token"`
	}

	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		utils.CustomError(w, "传递参数错误", http.StatusBadRequest)
		return
	}

	// 生成JWT token
	token, err := utils.RefreshToken(req.Token)
	if err != nil {
		utils.CustomError(w, "获取token失败", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(200)
	// 返回token和用户信息
	json.NewEncoder(w).Encode(map[string]interface{}{
		"status": 0,
		"msg":    "OK",
		"token":  token,
	})
}
